/**
 * @file ext-helloworld.js
 *
 * @license MIT
 *
 * @copyright 2010 Alexis Deveria
 *
 */
const name = 'helloworld'

const loadExtensionTranslation = async function (svgEditor) {
  let translationModule
  const lang = svgEditor.configObj.pref('lang')
  try {
    translationModule = await import(`./locale/${lang}.js`)
  } catch (_error) {
    console.warn(`Missing translation (${lang}) for ${name} - using 'en'`)
    translationModule = await import('./locale/en.js')
  }
  svgEditor.i18next.addResourceBundle(lang, name, translationModule.default)
}

export default {
  name,
  async init({
    _importLocale
  }) {
    const svgEditor = this
    await loadExtensionTranslation(svgEditor)

    const {
      svgCanvas
    } = svgEditor
    const {
      $id,
      $click,
      $qa,
      $
    } = svgCanvas

    const modeId = 'ems'
    const startClientPos = {}

    let curShape
    let startX
    let startY

    let curtId
    let lastBBox = {}
    let _data = new Map()

    return {
      //我有哦不可忽视的观看距离
      name: svgEditor.i18next.t(`${name}:name`),
      async callback () {
        $("#tools_rect").on('click',function(){
           $(this).find('.open').css({
             background:"cyan"
           })
        })

        const onClickHandler = (ev) => {
          ev.stopPropagation()
          this.currentAction = ev.target
          curtId = this.currentAction.id
          // 修改选中焦点
          if (this.leftPanel.updateLeftPanel(curtId)) {
            svgCanvas.setMode(modeId)
          }
        }

        //图元初始化加载
        async function Primitives() {

          const response = await fetch(`${svgEditor.configObj.curConfig.serviceUrl}/svg/primitive/list`)
          const data = (await response.json()).data;

          const buttonTemplate = document.createElement('template')

          Object.entries(data).forEach(([key, value]) => {
            value.forEach((gs) => {
              let title = gs.title;
              let content = gs.content;
              _data.set(id, content)
              if (!title) {
                return; //跳出循环
              }
              let encoded = btoa(unescape(encodeURIComponent(content)))
              buttonTemplate.innerHTML += `<se-button class="hello" id="${id}" title="${title}" data-type="${key}" src="data:image/svg+xml;base64,${encoded}"></se-button>`
            })
          })

          $('#tools_left .Primitives').append(buttonTemplate.content.cloneNode(true))


          $qa(".hello").forEach(e => {
            svgEditor.$click(e, onClickHandler)
          })

        }

        Primitives();
        $(".savePrimitives").on('click', function () {
          var url = `${svgEditor.configObj.curConfig.serviceUrl}/svg/graphics`
          // 当前图层
          const currentLayer = svgCanvas.getCurrentDrawing().getCurrentLayer()
          // 画布大小
          const [x, y] = svgEditor.configObj.curConfig.dimensions
          // 第一个g元素
          const firstChild = currentLayer.querySelector('g')
          svgCanvas.setStarted(true)
          // 添加选中元素
          svgCanvas.addToSelection([firstChild])
          // 左对齐
          svgCanvas.alignSelectedElements('l', 'page')
          // 顶部对齐
          svgCanvas.alignSelectedElements('t', 'page')

          let {width, height} = currentLayer.getBBox()
          width = Math.ceil(width),
          height = Math.ceil(height);

          // 保存时改变画布宽高
          // svgCanvas.setResolution(width, height)

          const origSource = svgCanvas.getSvgString();
          let svg = $(origSource);
          svg.attr({width, height})
          svg.find('title').remove();
          let origSourceString = svg.prop("outerHTML");

          svgCanvas.setStarted(true)
          // svgCanvas.setResolution(x, y)
          //svgCanvas.clear()
          let data = {
            type: 'HZT',
            name: '测试名称',
            content: `${origSourceString}`,
            id: '123'
          };

          let params = new URLSearchParams()
          for (let item in data) {
            params.append(item, data['' + item + ''])
          }
          fetch(url, {
              method: 'POST', // or 'PUT'
              body: params,
              headers: new Headers({
                'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
              })
            }).then(res => console.log(res))
            .catch(error => console.error('Error:', error))
            .then(response => console.log('Success:', response));





          // fetch(url, {
          //   method: 'POST', // or 'PUT'o'o
          //   body: JSON.stringify(data),
          //   headers: new Headers({
          //     'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
          //   })
          // }).then(res => console.log(res))
          // .catch(error => console.error('Error:', error))
          // .then(response => console.log('Success:', response));

        })


        $(".reloadPrimitives").on("click", function () {
          $(".Primitives *").not('span').remove();
          Primitives();


        })







      },
      // This is triggered when the main mouse button is pressed down
      // on the editor canvas (not the tool panels)
      mouseDown(opts) {
        const mode = svgCanvas.getMode()
        if (mode !== modeId) { return undefined }
        // The returned object must include "started" with
        // a value of true in order for mouseUp to be triggered
        startX = opts.start_x
        const x = startX
        startY = opts.start_y
        const y = startY

        startClientPos.x = opts.event.clientX
        startClientPos.y = opts.event.clientY

        const curContent = _data.get(curtId)
        const curType = $id(curtId).dataset.type
        const curStyle = svgCanvas.getStyle()

        let addGElement = (curShape, element) => {
          let children = $(element).find("g>*");
          $(children).each(function () {
            let tagName = this.tagName;
            if (tagName == 'g') {
              addGElement(curShape , this);
            } else {
              let newElement = $(this).clone().attr({
                "id": svgCanvas.getNextId(),
                "stroke-width": 2
              });
              $(curShape).append(newElement);
              if (tagName == "path") {
                let path = newElement[0]
                const d = newElement.attr("d");
                if (/[a-z]/.test(d)) {
                  const convertedPath = svgCanvas.pathActions.convertPath(path);
                  path.setAttribute('d', convertedPath);
                  svgCanvas.pathActions.fixEnd(path);
                }
                svgCanvas.recalculateDimensions(path);
              }
            }
          });
        };

        let elements = $(curContent).find("g>*");
        let elementLength = $(curContent).find("g>path").length;
        if (elements.length > 1 || elementLength != elements.length) {
          curShape = svgCanvas.addSVGElementsFromJson({
            "element": "g",
            "curStyles": true,
            "attr": {
              "id": svgCanvas.getNextId(),
              "docType": curType.replace("tool_", ""),
              'class': 'ems'
            }
          });
          addGElement(curShape, curContent);
        } else {
          let currentD = $(curContent).find('path').attr("d");
          curShape = svgCanvas.addSVGElementsFromJson({
            "element": "path",
            "curStyles": true,
            "attr": {
              "d": currentD,
              "id": svgCanvas.getNextId(),
              "opacity": curStyle.opacity / 2,
              "style": "pointer-events:none",
              "docType": curType.replace("tool_", ""),
              "stroke-width": 2,
              "fill": $(curContent).attr("fill"),
              "stroke": $(curContent).attr("stroke"),
              'class': 'ems'
            }
          });
          // Make sure shape uses absolute values
          if (/[a-z]/.test(currentD)) {
            currentD = svgCanvas.pathActions.convertPath(curShape);
            curShape.setAttribute('d', currentD);
            svgCanvas.pathActions.fixEnd(curShape);
          }
        }

        curShape.setAttribute('transform', 'translate(' + x + ',' + y + ') scale(0.005) translate(' + -x + ',' + -y + ')')

        svgCanvas.recalculateDimensions(curShape);

        lastBBox = curShape.getBBox();
        return {
          started: true
        };
      },
      mouseMove: function (opts) {
        const mode = svgCanvas.getMode()
        if (mode !== modeId) {
          return
        }

        const zoom = svgCanvas.getZoom()
        const evt = opts.event

        const x = opts.mouse_x / zoom
        const y = opts.mouse_y / zoom

        const tlist = curShape.transform.baseVal
        const box = curShape.getBBox()
        const left = box.x;
        const top = box.y

        const newBox = {
          x: Math.min(startX, x),
          y: Math.min(startY, y),
          width: Math.abs(x - startX),
          height: Math.abs(y - startY)
        }

        let sx = (newBox.width / lastBBox.width) || 1
        let sy = (newBox.height / lastBBox.height) || 1

        // Not perfect, but mostly works...
        let tx = 0
        if (x < startX) {
          tx = lastBBox.width
        }
        let ty = 0
        if (y < startY) {
          ty = lastBBox.height
        }

        // update the transform list with translate,scale,translate
        const translateOrigin = svgroot.createSVGTransform()
        const scale = svgroot.createSVGTransform()
        const translateBack = svgroot.createSVGTransform()

        translateOrigin.setTranslate(-(left + tx), -(top + ty))
        if (!evt.shiftKey) {
          const max = Math.min(Math.abs(sx), Math.abs(sy))

          sx = max * (sx < 0 ? -1 : 1)
          sy = max * (sy < 0 ? -1 : 1)
        }
        scale.setScale(sx, sy)

        translateBack.setTranslate(left + tx, top + ty)
        tlist.appendItem(translateBack)
        tlist.appendItem(scale)
        tlist.appendItem(translateOrigin)

        svgCanvas.recalculateDimensions(curShape)

        lastBBox = curShape.getBBox()
      },
      // This is triggered from anywhere, but "started" must have been set
      // to true (see above). Note that "opts" is an object with event info
      mouseUp(opts) {
        const mode = svgCanvas.getMode()
        if (mode !== modeId) {
          return undefined
        }

        const keepObject = (opts.event.clientX !== startClientPos.x && opts.event.clientY !== startClientPos.y)

        return {
          keep: keepObject,
          element: curShape,
          started: false
        }
      }
    }
  }
}
